package com.xunshibao.core.dao;

import java.lang.reflect.Method;
import java.util.List;

public class DaoUtils {
    public static void getUpdateFields(Object src, Object dest, List<String> columns, List<Object> values, List<String> props, boolean isInclude) {
        Class<?> cls = src.getClass();
        Method[] methods = cls.getMethods();
        if (methods != null) {
            Object srcV;
            Object destV;
            String methodName;
            String propname;
            for (Method method : methods) {
                methodName = method.getName();
                propname = methodName.substring(3,4).toLowerCase()+methodName.substring(4);
                try {
                    if (methodName.startsWith("get")) {
                        if (method != null) {
                            // 如果属性是被包含的,只比较props中指定的属性
                            if (isInclude) {
                                if (props.contains(propname)) {
                                    srcV = method.invoke(src, (Object[]) null);
                                    destV = method.invoke(dest, (Object[]) null);
                                    if (isNotEqual(srcV, destV)) {
                                        columns.add(methodName);
                                        values.add(destV);
                                    }
                                    props.remove(propname);
                                    if(props.isEmpty()) {
                                        break;
                                    }
                                }
                            } else {// 如果属性是不被包含的,则props中指定的属性不需要参与比较
                                if (!props.contains(propname)) {
                                    srcV = method.invoke(src, (Object[]) null);
                                    destV = method.invoke(dest, (Object[]) null);
                                    if (isNotEqual(srcV, destV)) {
                                        columns.add(methodName);
                                        values.add(destV);
                                    }
                                } else {
                                    props.remove(propname);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    private static boolean isNotEqual(Object src, Object desc) {
        if ((src == null && desc == null) || src.equals(desc)) {
            return false;
        } else {
            return true;
        }
    }

}
